// 框架使用示例

import {
  router,
  navigateTo,
  redirectTo,
  reLaunch,
  switchTab,
  back,
} from '@/router'
import {
  errorManager,
  handleError,
  createError,
  ErrorType,
} from '@/utils/error'
import {
  debounce,
  throttle,
  deepClone,
  formatMoney,
  maskPhone,
  validatePhone,
  validateEmail,
  generateId,
  generateUUID,
} from '@/utils/common'
import {
  LazyImageLoader,
  VirtualList,
  MemoryManager,
  PerformanceMonitor,
  lazyImageLoader,
} from '@/utils/performance'
import {
  SecurityUtils,
  XSSProtection,
  DataMasking,
  InputValidator,
} from '@/utils/security'
import { i18n, t, tPlural, setLanguage, getCurrentLanguage } from '@/i18n'
import {
  logManager,
  debugPanel,
  debug,
  info,
  warn,
  error as logError,
  showDebugPanel,
  toggleDebugPanel,
} from '@/utils/debug'

// 路由使用示例
export const routerExamples = {
  // 基本导航
  navigateToHome: () => navigateTo('/src/pages/index/index'),
  navigateToLogin: () => navigateTo('/src/pages/login/login'),

  // 重定向
  redirectToLogin: () => redirectTo('/src/pages/login/login'),

  // 重启应用
  restartApp: () => reLaunch('/src/pages/index/index'),

  // 切换标签页
  switchToHome: () => switchTab('/src/pages/index/index'),

  // 返回上一页
  goBack: () => back(),

  // 添加路由守卫
  addAuthGuard: () => {
    router.addGuard({
      beforeEnter: (to, from) => {
        console.log(`Navigating from ${from?.path} to ${to.path}`)
        return true
      },
    })
  },
}

// 错误处理示例
export const errorExamples = {
  // 处理网络错误
  handleNetworkError: (error: any) => {
    handleError(
      createError(ErrorType.NETWORK, '网络连接失败', 'NETWORK_ERROR', {
        url: error.url,
        status: error.status,
      })
    )
  },

  // 处理API错误
  handleApiError: (error: any) => {
    handleError(
      createError(ErrorType.API, error.message || 'API请求失败', error.code)
    )
  },

  // 处理验证错误
  handleValidationError: (field: string, message: string) => {
    handleError(
      createError(
        ErrorType.VALIDATION,
        `${field}: ${message}`,
        'VALIDATION_ERROR'
      )
    )
  },

  // 处理权限错误
  handlePermissionError: () => {
    handleError(
      createError(ErrorType.PERMISSION, '没有访问权限', 'PERMISSION_DENIED')
    )
  },
}

// 常用工具示例
export const commonExamples = {
  // 防抖搜索
  debouncedSearch: debounce((query: string) => {
    console.log('Searching for:', query)
  }, 300),

  // 节流滚动
  throttledScroll: throttle((event: any) => {
    console.log('Scroll position:', event.scrollTop)
  }, 100),

  // 深拷贝对象
  cloneUserData: (userData: any) => {
    return deepClone(userData)
  },

  // 格式化金额
  formatPrice: (amount: number) => {
    return formatMoney(amount, '¥')
  },

  // 脱敏手机号
  maskUserPhone: (phone: string) => {
    return maskPhone(phone)
  },

  // 验证输入
  validateUserInput: (input: { phone?: string; email?: string }) => {
    const errors: string[] = []

    if (input.phone && !validatePhone(input.phone)) {
      errors.push('手机号格式不正确')
    }

    if (input.email && !validateEmail(input.email)) {
      errors.push('邮箱格式不正确')
    }

    return errors
  },

  // 生成ID
  generateUserId: () => generateId(),
  generateSessionId: () => generateUUID(),
}

// 性能优化示例
export const performanceExamples = {
  // 图片懒加载
  setupLazyImages: () => {
    // #ifdef H5
    const images = document.querySelectorAll('img[data-src]')
    images.forEach((img) => {
      lazyImageLoader.observe(
        img as HTMLImageElement,
        img.getAttribute('data-src')!,
        img.getAttribute('data-placeholder') || undefined
      )
    })
    // #endif
  },

  // 虚拟列表
  createVirtualList: (
    container: HTMLElement,
    items: any[],
    renderItem: (item: any, index: number) => HTMLElement
  ) => {
    return new VirtualList(container, {
      itemHeight: 50,
      items,
      renderItem,
    })
  },

  // 内存缓存
  cacheData: (key: string, data: any, ttl?: number) => {
    MemoryManager.set(key, data, ttl)
  },

  getCachedData: (key: string) => {
    return MemoryManager.get(key)
  },

  // 性能监控
  measureFunction: async (name: string, fn: () => Promise<any>) => {
    return PerformanceMonitor.measureAsync(name, fn)
  },

  startTimer: (name: string) => {
    PerformanceMonitor.start(name)
  },

  endTimer: (name: string) => {
    return PerformanceMonitor.end(name)
  },
}

// 安全工具示例
export const securityExamples = {
  // 数据加密
  encryptData: (data: string, key: string) => {
    return SecurityUtils.xorEncrypt(data, key)
  },

  decryptData: (encryptedData: string, key: string) => {
    return SecurityUtils.xorDecrypt(encryptedData, key)
  },

  // XSS防护
  sanitizeInput: (input: string) => {
    return XSSProtection.sanitizeInput(input, {
      allowHtml: false,
      maxLength: 1000,
    })
  },

  // 数据脱敏
  maskSensitiveData: (data: {
    phone?: string
    email?: string
    idCard?: string
  }) => {
    return {
      phone: data.phone ? DataMasking.maskPhone(data.phone) : undefined,
      email: data.email ? DataMasking.maskEmail(data.email) : undefined,
      idCard: data.idCard ? DataMasking.maskIdCard(data.idCard) : undefined,
    }
  },

  // 输入验证
  validateForm: (formData: {
    username: string
    password: string
    email: string
  }) => {
    const usernameValidation = InputValidator.validateUsername(
      formData.username
    )
    const passwordValidation = InputValidator.validatePassword(
      formData.password
    )
    const emailValidation = InputValidator.validateEmail(formData.email)

    return {
      valid:
        usernameValidation.valid && passwordValidation.valid && emailValidation,
      errors: [
        ...usernameValidation.errors,
        ...passwordValidation.errors,
        ...(emailValidation ? [] : ['邮箱格式不正确']),
      ],
    }
  },
}

// 国际化示例
export const i18nExamples = {
  // 切换语言
  switchToEnglish: () => setLanguage('en-US'),
  switchToChinese: () => setLanguage('zh-CN'),

  // 获取翻译
  getTranslation: (key: string, params?: any) => {
    return t(key, params)
  },

  // 复数翻译
  getPluralTranslation: (key: string, count: number, params?: any) => {
    return tPlural(key, count, params)
  },

  // 获取当前语言
  getCurrentLang: () => getCurrentLanguage(),

  // 检查翻译是否存在
  hasTranslation: (key: string) => {
    return i18n.hasTranslation(key)
  },
}

// 调试工具示例
export const debugExamples = {
  // 日志记录
  logDebug: (message: string, data?: any) => {
    debug(message, data)
  },

  logInfo: (message: string, data?: any) => {
    info(message, data)
  },

  logWarning: (message: string, data?: any) => {
    warn(message, data)
  },

  logError: (message: string, data?: any) => {
    logError(message, data)
  },

  // 调试面板
  showPanel: () => showDebugPanel(),
  togglePanel: () => toggleDebugPanel(),

  // 性能监控
  measurePerformance: (name: string, fn: () => void) => {
    const start = performance.now()
    fn()
    const end = performance.now()
    debug(`Performance: ${name}`, { duration: end - start })
  },
}

// 综合使用示例
export const comprehensiveExample = {
  // 用户登录流程
  loginUser: async (credentials: { username: string; password: string }) => {
    try {
      // 开始性能监控
      PerformanceMonitor.start('user-login')

      // 验证输入
      const validation = securityExamples.validateForm({
        username: credentials.username,
        password: credentials.password,
        email: '',
      })

      if (!validation.valid) {
        errorExamples.handleValidationError(
          'login',
          validation.errors.join(', ')
        )
        return false
      }

      // 记录登录尝试
      debug('User login attempt', { username: credentials.username })

      // 模拟API调用
      const response = await fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify(credentials),
      })

      if (!response.ok) {
        errorExamples.handleApiError({
          message: '登录失败',
          code: response.status,
        })
        return false
      }

      const userData = await response.json()

      // 缓存用户数据
      performanceExamples.cacheData('user-info', userData, 30 * 60 * 1000) // 30分钟

      // 记录成功登录
      info('User login successful', { userId: userData.id })

      // 结束性能监控
      const duration = PerformanceMonitor.end('user-login')
      debug('Login performance', { duration })

      // 导航到首页
      await routerExamples.navigateToHome()

      return true
    } catch (error) {
      errorExamples.handleNetworkError(error)
      return false
    }
  },

  // 数据展示页面
  setupDataPage: (container: HTMLElement, data: any[]) => {
    // 设置懒加载
    performanceExamples.setupLazyImages()

    // 创建虚拟列表
    const virtualList = performanceExamples.createVirtualList(
      container,
      data,
      (item, index) => {
        const element = document.createElement('div')
        element.innerHTML = `
          <div class="data-item">
            <h3>${i18nExamples.getTranslation('common.item')} ${index + 1}</h3>
            <p>${item.description}</p>
            <img data-src="${
              item.image
            }" data-placeholder="/placeholder.jpg" alt="Item image">
          </div>
        `
        return element
      }
    )

    // 设置搜索防抖
    const searchInput = container.querySelector(
      'input[type="search"]'
    ) as HTMLInputElement
    if (searchInput) {
      searchInput.addEventListener('input', (event: Event) => {
        const target = event.target as HTMLInputElement
        commonExamples.debouncedSearch(target.value)
      })
    }

    return virtualList
  },
}

// 导出所有示例
export default {
  router: routerExamples,
  error: errorExamples,
  common: commonExamples,
  performance: performanceExamples,
  security: securityExamples,
  i18n: i18nExamples,
  debug: debugExamples,
  comprehensive: comprehensiveExample,
}
